// pages/restaurant/shop/shopDetail/component/settlement.js
const app = getApp();
const util = require('../../utils/util')
import {
  addCart,
  getCart,
  count,
  update,
  del
} from "../../api/cart"
import { find } from '../../api/shop'

Component({
  /**
   * 组件的属性列表
   */
  properties: {
    shopId: {
      type: String,
      value: "",
      observer:function(news, old, path){
        this.setData({
          currentShopId: news 
        })
}
    },
    cartX: {
      type: String,
      value: 5
    },
    cartY: {
      type: String,
      value: 95
    }
  },

  observers: {
    'currentShopId': function (shopId) {
      this.cartHandlerWithoutAnimation()          
    }
},

  /**
   * 组件的初始数据
   */
  data: {
    totalAmount: 0,
    discount: 0,
    flag: false,
    wrapAnimate: "",
    maskAnimate: "",

    cartIconUrl: util.thumbnail(app.APP_OSSURL_API+"/dinnerBar/canyin/gouwuche_bg%402x.png",  80, 80),
    clearCartIconUrl: app.APP_OSSURL_API + "/dinnerBar/canyin/canyin-qingkonggouwuche.png",
    reduceIconUrl: app.APP_OSSURL_API + "/dinnerBar/canyin/canyin-shuliang-.png",
    plusIconUrl: app.APP_OSSURL_API + "/dinnerBar/canyin/canyin-shuliang%2B.png",

    productList: [],
    productName: "",
    sku: "",
    productNum: 0,
    price: 0,
    delivery: 0,
    count:0,

    hide_good_box: true,
    feiBox: "",
    bus_x: "",
    bus_y: "",

    currentShopId:"",
    minimumDelivery:0,
    workBeginTime : "",
    workEndTime:"",
    isSaleTime:true,
    canShippingMake:false,
    shopStatus:true,
    isWorking:true,
    notice:"本店已休息"
  },

  attached() {
    console.info("购物车的请求发送了")
    // this.getCart()
    // this.getCount()
  },

  /**
   * 组件的方法列表
   */
  methods: {

    //检测用户的登陆状态
  checkLogin(callback) {
    console.info("全局变量app.globalData--" + JSON.stringify(app.globalData))
    if (app.globalData.token == null) {
      wx.navigateTo({
        url: '/pages/login/index',
      })
    } else {
      if (callback) {
        callback()
      }
    }
  },

    //不执行动画更新购物车
    cartHandlerWithoutAnimation(){
      this.getCart()
      this.getCount()
      this.getShopInfo()
    },

    // 获取商店信息
    getShopInfo(shopId) {
      let _this = this
      find(this.data.currentShopId).then(
          res => {
              console.info("我是购物车获取商店信息--")
              console.info(res)
              if (res.type == 'success') {
                let workBeginTime = ""
                let workEndTime = ""
                if(!util.isNull(res.data.shop.shippingConfig)){
                  let shippingConfig = JSON.parse(res.data.shop.shippingConfig)
                  if(!util.isNull(shippingConfig.workBeginTime)&&!util.isNull(shippingConfig.workEndTime)){
                      workBeginTime = shippingConfig.workBeginTime
                      workEndTime = shippingConfig.workEndTime
                  }
                  if(shippingConfig.shippingmake>0){
                    _this.data.canShippingMake = true
                  }
              }
                  _this.setData({
                    minimumDelivery:res.data.shop.minimumDelivery,
                    workBeginTime:workBeginTime,
                    workEndTime:workEndTime,
                    canShippingMake:_this.data.canShippingMake,
                    shopStatus:res.data.shop.status==1?true:false,
                    isWorking:res.data.shop.paused==0?true:false,
                    notice:util.isNull(res.data.shop.notice)?_this.data.notice:res.data.shop.notice
                  })
                  _this.isWorkTime()
                  if(callback){
                      callback(res.data)
                  }
              }
          }
      ).catch(error => { })
  },

    //更新购物车信息
    cartHandler(data) {
      this.getCart()
      // this.getCount()
      console.info(data)
      if (data.type == "add") {
        this.touchOnGoods(data)
      } else if ((data.type == "reduce")) {
        this.getCount()
      }
    },

    //获取购物车商品
    getCart(callback) {
      let params = {
        shopId: this.data.currentShopId,
        uuid: app.globalData.uuid
      }
      getCart(params).then(
        res => {
          console.log("我是组件的getCart--")
          console.log(res)
          if (res.type == 'success') {
            let productList = []
            if(res.data.cart.itemVoList.length > 0){
              res.data.cart.itemVoList.map(item => {
                if(item.quantity > 0&& item.stock>0){
                  productList.push({...item,thumbnail:util.thumbnail(item.thumbnail,125,125)} )
                }
              })
              this.setData({
                productList: productList

              })
            }else{
              this.setData({
                productList: []
              })
            }
            if(callback){
              callback(res.data)
            }
            
          }
        }
      ).catch(error => {})
    },

    //获取购物车中的商品总数量
    getCount() {
      let params = {
        shopId: this.data.currentShopId,
        uuid: app.globalData.uuid
      }
      count(params).then(
        res => {
          console.log("count--" + JSON.stringify(res))
          if (res.type == 'success') {
            this.setData({
              count: res.data.quantity,
              totalAmount: res.data.amount
            })
          }
        }
      ).catch(error => {})
    },

    //添加购物车商品
    addCart(productId, callback) {
      let params = {
        shopId: this.data.currentShopId,
        productId: productId,
        quantity: 1,
        uuid: app.globalData.uuid
      }
      addCart(params).then(
        res => {
          // console.log("我是组件的getCart--" + JSON.stringify(res))
          if (res.type == 'success') {
            if (callback) {
              callback()
            }
          }
        }
      ).catch(error => {})
    },

    //添加购物车商品
    reduceCart(info, callback) {
      let _this = this
      let data = [{
        id: info.cartId,
        quantity: info.quantity - 1,
        chk: true
      }]
      update(data).then(
        res => {
          // console.log("我是组件的getCart--" + JSON.stringify(res))
          if (res.type == 'success') {
            _this.getCart(()=>{
              if(this.data.productList.length == 0){
                _this.openSelectProductDialog()
                }
              }
            )
          _this.getCount()
          _this.triggerEvent('getCart', _this.data.shopId)
            if (callback) {
              callback()
            }
          }
        }
      ).catch(error => {})
    },

    cleanCart(){
      let _this = this
      wx.showModal({
        title: '提示',
        content: '确认要清空购物车',
        success (res) {
          if (res.confirm) {
            let ids = []
      console.info(_this.data.productList)
      if(_this.data.productList.length > 0){
        _this.data.productList.map(item => {
          ids.push(item.id)
        })
      }
      del(ids).then(
        res => {
          if (res.type == 'success') {
            console.info(res)
            _this.getCart(()=>{
              console.info("this.data.productList-------")
              console.info(_this.data.productList.length)
              if(_this.data.productList.length == 0){
                _this.openSelectProductDialog()
                }
            })
            _this.getCount()
            _this.triggerEvent('getCart', _this.data.shopId)
          }
        }
      ).catch(error => {})
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
      
    },

    //删除购物车商品
    deleteCart(info, callback) {
      let _this = this
      let data = [info.cartId]
      del(data).then(
        res => {
          // console.log("我是组件的getCart--" + JSON.stringify(res))
          if (res.type == 'success') {
            _this.getCart(()=>{
              if(this.data.productList.length == 0){
              _this.openSelectProductDialog()
              }
            })
          _this.getCount()
          _this.triggerEvent('getCart', _this.data.shopId)
            if (callback) {
              callback()
            }
          }
        }
      ).catch(error => {})
    },

    //判断是否在营业时间内
    isWorkTime(){
      let _this = this
      let now = new Date()
      let nowTime = now.getTime()
      if(!util.isNull(_this.data.workBeginTime)&&!util.isNull(_this.data.workEndTime)){

      let today = now.getFullYear()+"/"+(now.getMonth()+1)+"/"+now.getDate()
      let begin = new Date(today + " " + this.data.workBeginTime).getTime()
      let end = new Date(today + " " + this.data.workEndTime).getTime()

      if(end<begin){
        //这个时候就有两个时间段，是0点到end和begin到12点的时间
        let zeroPoint = new Date(new Date().toLocaleDateString()).getTime()
        let tomorrowPoint = zeroPoint+24*60*60*1000
        console.info("---------------------------------------------------")
        console.info("zeroPoint--"+zeroPoint)
        console.info("end--"+end)
        console.info("begin--"+begin)
        console.info("tomorrowPoint--"+tomorrowPoint)
        console.info("---------------------------------------------------")
        if(nowTime>zeroPoint&&nowTime<end){
          this.setData({
            isSaleTime:true
          })
          return true
        }else if(nowTime>begin&&nowTime<tomorrowPoint){
          this.setData({
            isSaleTime:true
          })
          return true
        }else{
          this.setData({
            isSaleTime:false
          })
          return false
        }
      }else{
        //介于开始和结束直接就是营业时间
        if(nowTime>begin && nowTime<end){
          this.setData({
            isSaleTime:true
          })
          return true
        }else{
          this.setData({
            isSaleTime:false
          })
          return false
        }
      }
      console.info("---------------------------------------------------")
      console.info("nowTime--"+nowTime)
      console.info("begin--"+begin)
      console.info("end--"+end)
      console.info("---------------------------------------------------")
      
      }
      this.setData({
        isSaleTime:true
      })
      return true
    },

    createOrder() {
      let _this = this
      this.checkLogin(()=>{
        if(_this.isWorkTime() || _this.data.canShippingMake){

        
        if(this.data.productList.length > 0){
          wx.navigateTo({
            url: '/pages/shop/settlement/index?shopId=' + this.data.shopId,
          })
        }else{
          wx.showToast({
            title: '请先加购菜品',
            icon:"none"
          })
        }
      }else{
        wx.showToast({
          title: '目前是非营业时间',
          icon:"none"
        })
      }
      })
    },

    openSelectProductDialog() {
      console.info("this.data.wrapAnimate--" + this.data.wrapAnimate)
      console.info("this.data.productList.length--" + this.data.productList.length)
        if (this.data.wrapAnimate == "comeIn") {
          // if(this.data.productList.length == 0){
            this.setData({
              wrapAnimate: "comeOut",
              maskAnimate: "maskAnimateOut",
            })
            setTimeout(() => {
              this.setData({
                flag: false
              })
            }, 550)
        } else {
          if(this.data.productList.length > 0){
          this.setData({
            wrapAnimate: "comeIn",
            flag: true
          })
        }
        }
    },

    maskclick() {
      this.setData({
        wrapAnimate: "comeOut",
        maskAnimate: "maskAnimateOut",
      })
      setTimeout(() => {
        this.setData({
          flag: false
        })
      }, 550)
    },

    reduceNum(e) {
      let _this = this
      console.info(e)
      let data = {
        cartId: e.currentTarget.dataset.item.id,
        quantity: e.currentTarget.dataset.item.quantity
      }
      if (data.quantity - 1 > 0) {
        console.info("哈哈哈哈哈哈哈哈哈哈哈")
        _this.reduceCart(data)
      } else {
        console.info("呵呵呵呵呵呵呵呵呵呵呵呵呵")
        _this.deleteCart(data)
      }
    },

    addNum(e) {
      console.info(e)
      let _this = this
      let maxLimit = e.currentTarget.dataset.item.maxLimit
      let minLimit = e.currentTarget.dataset.item.minLimit
      if(maxLimit == e.currentTarget.dataset.item.quantity&&maxLimit>0){
        wx.showToast({
          title: `该菜品限购${maxLimit}件哦！`,
          duration: 2000,
          icon: "none",
        })
}else{                  
      let data = {
        clientX: e.touches[0].clientX,
        clientY: e.touches[0].clientY
      }
      let productId = e.currentTarget.dataset.item.productId
      _this.addCart(productId, () => {
        _this.getCart()
        _this.triggerEvent('getCart', _this.data.shopId)
        _this.touchOnGoods(data)
      })
    }
    },

    //点击商品触发的事件
    touchOnGoods: function (data) {
      //把点击每一项的对应的商品图保存下来，就是飞向购物车的图片
      // this.setData({
      //         feiBox: this.data.imgUrls[e.currentTarget.dataset.idx]
      // })
      // 如果good_box正在运动
      this.busPos = {};
      this.busPos['x'] = app.globalData.ww * parseInt(this.data.cartX) * 0.01; //目标位置的x坐标
      this.busPos['y'] = app.globalData.hh * parseInt(this.data.cartY) * 0.01; //目标位置的y坐标
      console.info("data" + JSON.stringify(data))
      if (!this.data.hide_good_box) return;
      //当前点击位置的x，y坐标
      this.finger = {};
      var topPoint = {};
      this.finger['x'] = data.clientX;
      this.finger['y'] = data.clientY - 20;

      if (this.finger['y'] < this.busPos['y']) {
        topPoint['y'] = this.finger['y'] - 150;
      } else {
        topPoint['y'] = this.busPos['y'] - 150;
      }

      if (this.finger['x'] < this.busPos['x']) {
        topPoint['x'] = Math.abs(this.finger['x'] - this.busPos['x']) / 2 + this.finger['x'];
        this.linePos = this.bezier([this.finger, topPoint, this.busPos], 60);
        this.startAnimationLeft();
      } else {
        topPoint['x'] = Math.abs(this.finger['x'] - this.busPos['x']) / 2 + this.busPos['x'];
        this.linePos = this.bezier([this.busPos, topPoint, this.finger], 60);
        this.startAnimationRight();
      }

    },

    //从左开始动画
    startAnimationLeft: function () {
      var index = 0,
        that = this,
        bezier_points = that.linePos['bezier_points'];
      this.setData({
        hide_good_box: false,
        bus_x: that.finger['x'],
        bus_y: that.finger['y']
      })
      this.timer = setInterval(function () {
        index++;
        that.setData({
          bus_x: bezier_points[index]['x'],
          bus_y: bezier_points[index]['y']
        })
        if (index >= 29) {
          clearInterval(that.timer);
          this.getCount()
          that.setData({
            hide_good_box: true,
          })
        }
      }, 20);
    },

    //从右开始动画
    startAnimationRight: function () {
      var index = 0,
        that = this,
        bezier_points = that.linePos['bezier_points'];
      console.info(bezier_points)
      var len = bezier_points.length;
      this.setData({
        hide_good_box: false,
        bus_x: that.busPos['x'],
        bus_y: that.busPos['y']
      })
      this.timer = setInterval(function () {
        console.info("我被执行了")
        index++;
        that.setData({
          bus_x: bezier_points[len - index]['x'],
          bus_y: bezier_points[len - index]['y']
        })
        if (index >= 59) {
          clearInterval(that.timer);
          that.getCount()
          that.setData({
            hide_good_box: true,
          })
        }
      }, 10);
    },

    //用于添加购物车的动画效果
    bezier: function (points, times) {
      // 0、以3个控制点为例，点A,B,C,AB上设置点D,BC上设置点E,DE连线上设置点F,则最终的贝塞尔曲线是点F的坐标轨迹。
      // 1、计算相邻控制点间距。
      // 2、根据完成时间,计算每次执行时D在AB方向上移动的距离，E在BC方向上移动的距离。
      // 3、时间每递增100ms，则D,E在指定方向上发生位移, F在DE上的位移则可通过AD/AB = DF/DE得出。
      // 4、根据DE的正余弦值和DE的值计算出F的坐标。
      // 邻控制AB点间距
      var bezier_points = [];
      var points_D = [];
      var points_E = [];
      const DIST_AB = Math.sqrt(Math.pow(points[1]['x'] - points[0]['x'], 2) + Math.pow(points[1]['y'] - points[0]['y'], 2));
      // 邻控制BC点间距
      const DIST_BC = Math.sqrt(Math.pow(points[2]['x'] - points[1]['x'], 2) + Math.pow(points[2]['y'] - points[1]['y'], 2));
      // D每次在AB方向上移动的距离
      const EACH_MOVE_AD = DIST_AB / times;
      // E每次在BC方向上移动的距离
      const EACH_MOVE_BE = DIST_BC / times;
      // 点AB的正切
      const TAN_AB = (points[1]['y'] - points[0]['y']) / (points[1]['x'] - points[0]['x']);
      // 点BC的正切
      const TAN_BC = (points[2]['y'] - points[1]['y']) / (points[2]['x'] - points[1]['x']);
      // 点AB的弧度值
      const RADIUS_AB = Math.atan(TAN_AB);
      // 点BC的弧度值
      const RADIUS_BC = Math.atan(TAN_BC);
      // 每次执行
      for (var i = 1; i <= times; i++) {
        // AD的距离
        var dist_AD = EACH_MOVE_AD * i;
        // BE的距离
        var dist_BE = EACH_MOVE_BE * i;
        // D点的坐标
        var point_D = {};
        point_D['x'] = dist_AD * Math.cos(RADIUS_AB) + points[0]['x'];
        point_D['y'] = dist_AD * Math.sin(RADIUS_AB) + points[0]['y'];
        points_D.push(point_D);
        // E点的坐标
        var point_E = {};
        point_E['x'] = dist_BE * Math.cos(RADIUS_BC) + points[1]['x'];
        point_E['y'] = dist_BE * Math.sin(RADIUS_BC) + points[1]['y'];
        points_E.push(point_E);
        // 此时线段DE的正切值
        var tan_DE = (point_E['y'] - point_D['y']) / (point_E['x'] - point_D['x']);
        // tan_DE的弧度值
        var radius_DE = Math.atan(tan_DE);
        // 地市DE的间距
        var dist_DE = Math.sqrt(Math.pow((point_E['x'] - point_D['x']), 2) + Math.pow((point_E['y'] - point_D['y']), 2));
        // 此时DF的距离
        var dist_DF = (dist_AD / DIST_AB) * dist_DE;
        // 此时DF点的坐标
        var point_F = {};
        point_F['x'] = dist_DF * Math.cos(radius_DE) + point_D['x'];
        point_F['y'] = dist_DF * Math.sin(radius_DE) + point_D['y'];
        bezier_points.push(point_F);
        // console.info("point_F" + JSON.stringify(point_F) )
      }
      return {
        'bezier_points': bezier_points
      };
    },
  }
})